package com.errol.sync.sync.extension;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.mapper.Condition;
import com.renjia.supervise.entity.CoreUser;
import com.renjia.supervise.mapper.CoreUserMapper;
import com.renjia.supervise.service.sync.DatabaseSyncService;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author zhang xiao bin
 * @version v1.0
 * @date 2021/08/23
 * @since v
 **/
@Service("userSyncService")
public class UserSyncServiceImpl extends AlwaysFullSyncServiceImpl {

    private final CoreUserMapper coreUserMapper;

    public UserSyncServiceImpl(com.renjia.supervise.service.sync.DatabaseSyncService databaseSyncService, CoreUserMapper coreUserMapper) {
        super(databaseSyncService);
        this.coreUserMapper = coreUserMapper;
    }

    @Override
    public <E> String syncData(Class<E> entityClass, LocalDate rangeLeft, LocalDate rangeRight, boolean updateEditedData) {
        if (entityClass != CoreUser.class) {
            return "错误的实体类型";
        }
        return super.syncData(entityClass, rangeLeft, rangeRight, updateEditedData);
    }

    /**
     * 数据量少直接全量同步
     * 特殊处理 password，保留旧数据的值，新数据默认 123456 的md5
     */
    @Override
    protected void onDataLoaded(List<Map<String, Object>> loadedData, boolean isNewData) {
        Map<String, CoreUser> userMap = coreUserMapper.selectList(Condition.<CoreUser>wrapper().setSqlSelect("id,password"))
                .stream().collect(Collectors.toMap(CoreUser::getId, Function.identity()));
        loadedData.forEach(m -> {
            String id = (String) m.get("id");
            if (userMap.containsKey(id)) {
                m.put("password", userMap.get(id).getPassword());
            } else {
                m.put("password", SecureUtil.md5("123456"));
            }
        });
    }
}
